#include "datamonitor.h"
#include "ui_datamonitor.h"

DataMonitor::DataMonitor(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DataMonitor)
        , m_gridRow(0)
        , m_gridCol(0)
        , m_maxCols(1)  // 关键：设置为单列布局
        , m_chartCount(0)
{

    ui->setupUi(this);
    m_pLog = LogClass::getInstance();
    m_pSerialManage = new SerialPortManage(this);
    m_pSqliteManage = new SqliteManage;
    // 连接数据库
    if (!m_pSqliteManage->openDatabase("C:/Users/shafl/Desktop/FrameWork/test.db")) {
        QMessageBox::critical(this, "错误", "数据库连接失败：" + m_pSqliteManage->lastError());
    }
    m_historyDataWidget = new HistoryDataWidget(this);


    // 主布局：左右分割（左侧固定宽度，右侧自适应）
    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(2, 2, 2, 2);
    mainLayout->setSpacing(2);

    // ===== 左侧控制面板 =====
    QWidget *leftPanel = new QWidget(this);
    leftPanel->setMinimumWidth(220);  // 固定宽度
    leftPanel->setMaximumWidth(220);
    QVBoxLayout *leftLayout = new QVBoxLayout(leftPanel);
    leftLayout->setContentsMargins(3, 3, 3, 3);
    leftLayout->setSpacing(5);

    // 工具栏（带图标按钮）
    QHBoxLayout *toolbarLayout = new QHBoxLayout();
    toolbarLayout->setSpacing(3);

    m_addConfigButton = createToolButton(QIcon(":/icons/add.png"), "添加配置");
    m_editConfigButton = createToolButton(QIcon(":/icons/edit.png"), "编辑配置");
    m_deleteConfigButton = createToolButton(QIcon(":/icons/delete.png"), "删除配置");

    toolbarLayout->addWidget(m_addConfigButton);
    toolbarLayout->addWidget(m_editConfigButton);
    toolbarLayout->addWidget(m_deleteConfigButton);
    toolbarLayout->addStretch();

    leftLayout->addLayout(toolbarLayout);

    m_treeWidget = new QTreeWidget(this);
    m_treeWidget->setHeaderHidden(true);  // 隐藏表头
    m_treeWidget->setColumnCount(1);
    m_treeWidget->setAnimated(true);
    m_treeWidget->setIndentation(12);
    leftLayout->addWidget(m_treeWidget, 1);  // 占据剩余空间

    // 操作按钮区域
    m_addButton = new QPushButton("添加查看", this);
    m_addButton->setEnabled(false);
    m_addButton->setIcon(QIcon(":/icons/chart.png"));
    leftLayout->addWidget(m_addButton);

    mainLayout->addWidget(leftPanel);

    // ===== 右侧 =====
    QWidget *rightPanel = new QWidget(this);
    QVBoxLayout *rightLayout = new QVBoxLayout(rightPanel);
    rightLayout->setContentsMargins(5, 5, 5, 5);
    rightLayout->setSpacing(5);

    // 选项卡式界面
    QTabWidget *tabWidget = new QTabWidget(this);

    // 实时数据标签页
    QWidget *realtimeTab = new QWidget();
    QVBoxLayout *realtimeLayout = new QVBoxLayout(realtimeTab);

    // 图表区域
    m_scrollArea = new QScrollArea();
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setFrameShape(QFrame::NoFrame);

    m_chartContainer = new QWidget();
    m_chartLayout = new QGridLayout(m_chartContainer);
    m_chartLayout->setSpacing(10);
    m_chartLayout->setAlignment(Qt::AlignTop);  // 顶部对齐

    m_scrollArea->setWidget(m_chartContainer);
    realtimeLayout->addWidget(m_scrollArea);

    tabWidget->addTab(realtimeTab, QIcon(":/icons/realtime.png"), "实时数据");

    // 历史数据标签页
    tabWidget->addTab(m_historyDataWidget, QIcon(":/icons/history.png"), "历史数据");

    rightLayout->addWidget(tabWidget);
    mainLayout->addWidget(rightPanel, 1);  // 占据剩余空间

    // 窗口属性
    setWindowTitle("环境监控系统");
    setWindowIcon(QIcon(":/icons/app.png"));
    resize(1024, 680);

    // 初始化
    initStyles();
    loadSerialConfigs();

    connect(m_treeWidget, &QTreeWidget::itemSelectionChanged, this, &DataMonitor::onTreeItemSelected);
    connect(m_addConfigButton, &QPushButton::clicked, this, &DataMonitor::addSerialConfig);
    connect(m_editConfigButton, &QPushButton::clicked, this, &DataMonitor::editSerialConfig);
    connect(m_deleteConfigButton, &QPushButton::clicked, this, &DataMonitor::deleteSerialConfig);
    connect(m_addButton, &QPushButton::clicked, this, &DataMonitor::addMonitorPoint);
}

// 创建统一风格的工具栏按钮
QPushButton* DataMonitor::createToolButton(const QIcon &icon, const QString &text)
{
    QPushButton *btn = new QPushButton(text, this);
    btn->setIcon(icon);
    //btn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    btn->setStyleSheet(
        "QPushButton {"
        "  padding: 3px 6px;"
        "  text-align: left;"
        "  border: 1px solid #c0c0c0;"
        "  border-radius: 3px;"
        "}"
        "QPushButton:hover {"
        "  background-color: #e0e0e0;"
        "}");
    btn->setMinimumHeight(24);
    return btn;
}

// 初始化界面样式
void DataMonitor::initStyles()
{
    // 全局字体
    QFont font("Microsoft YaHei", 9);
    qApp->setFont(font);

    // 树控件样式
    m_treeWidget->setStyleSheet(
        "QTreeWidget {"
        "  border: 1px solid #d0d0d0;"
        "  border-radius: 3px;"
        "}"
        "QTreeWidget::item {"
        "  padding: 3px 1px;"
        "}");
}

DataMonitor::~DataMonitor()
{
    delete ui;
    delete m_pSerialManage;
    m_pSqliteManage->closeDatabase();
    m_pSerialManage = nullptr;
}

void DataMonitor::setUserName(QString &name)
{
    this->username = name;
    m_historyDataWidget->setUserName(name);
}

void DataMonitor::onTreeItemSelected()
{
    // 获取选中的项
    QList<QTreeWidgetItem*> selectedItems = m_treeWidget->selectedItems();

    // 只有选中项时才启用添加按钮
    m_addButton->setEnabled(selectedItems.size() == 1);
}

void DataMonitor::addMonitorPoint()
{
    // 获取选中的项
    QList<QTreeWidgetItem*> selectedItems = m_treeWidget->selectedItems();
    if (selectedItems.size() != 1)
        return;
    QTreeWidgetItem *item = selectedItems.first();
    int configId = item->data(0, Qt::UserRole).toInt();
    // 查找对应的串口配置
    SerialConfig config;
    bool found = false;
    for (const SerialConfig &c : m_serialConfigs) {
        if (c.id == configId) {
            config = c;
            found = true;
            break;
        }
    }
    if (!found)
        return;
    // 检查是否已添加该监控点
    for (MonitorPointWidget *widget : m_monitorWidgets) {
        if (widget->config().id == configId) {
            // 已经添加，滚动到该监控点并选中
            ensureWidgetVisible(widget);
            return;
        }
    }
    // 创建新的监控点小部件
    MonitorPointWidget *monitorWidget = new MonitorPointWidget(config, this);
    // 创建数据读取器
    DataReader *reader = new DataReader(config, this);
    monitorWidget->setDataReader(reader);
    // 将监控点添加到布局
    m_chartLayout->addWidget(monitorWidget, m_gridRow, 0);
    // 更新网格位置
    m_gridRow++;

    // 保存监控点小部件的引用
    m_monitorWidgets.append(monitorWidget);
    // 连接关闭信号
    connect(monitorWidget, &MonitorPointWidget::monitorClosed, this, &DataMonitor::removeMonitorPoint);
    connect(monitorWidget, &MonitorPointWidget::sendDataPoint, this, [=](const DataPoint &data){
        qDebug()<<"发送信号："<<config.device_id;
        int deviceid = config.device_id;
        emit sendDataPoint(deviceid,data);
    });
    // 增加图表计数
    m_chartCount++;
    // 调整滚动区域大小
    adjustScrollAreaSize();
    QTimer::singleShot(100, [this]() {
        m_scrollArea->verticalScrollBar()->setValue(
            m_scrollArea->verticalScrollBar()->maximum()
        );
    });
}

void DataMonitor::removeMonitorPoint(MonitorPointWidget *widget)
{
    // 从布局中移除
    m_chartLayout->removeWidget(widget);

    // 从列表中移除
    m_monitorWidgets.removeOne(widget);

    // 调整滚动区域大小
    adjustScrollAreaSize();

    // 更新网格布局
    rearrangeGridLayout();
}

void DataMonitor::addSerialConfig()
{
    SerialConfigDialog dialog(this);

    if (dialog.exec() == QDialog::Accepted) {
        SerialConfig config = dialog.getConfig();
        int tempId = -1;
        if(m_pSqliteManage->getDeviceIdByName(config.name,tempId)){
            config.device_id = tempId;
            // 添加到数据库
            if (m_pSqliteManage->addSerialConfig(config)) {
                // 重新加载配置
                m_pLog->log(m_pSqliteManage,OPERATION_LOG,INFO,QString("添加设备串口配置"),m_pSqliteManage->getUserIdByName(username),config.device_id);
                loadSerialConfigs();
            } else {
                QMessageBox::critical(this, "错误", "无法添加串口配置");
                return;
            }
        }else{
            QMessageBox::critical(this, "错误", "没有找到该设备");
        }
    }
}

void DataMonitor::editSerialConfig()
{
    // 获取选中的项
    QList<QTreeWidgetItem*> selectedItems = m_treeWidget->selectedItems();

    if (selectedItems.size() != 1)
        return;

    QTreeWidgetItem *item = selectedItems.first();
    int configId = item->data(0, Qt::UserRole).toInt();

    // 查找对应的串口配置
    SerialConfig config;
    bool found = false;

    for (const SerialConfig &c : m_serialConfigs) {
        if (c.id == configId) {
            config = c;
            found = true;
            break;
        }
    }
    if (!found)
        return;
    // 创建对话框并设置当前配置
    SerialConfigDialog dialog(this);
    dialog.setConfig(config);
    if (dialog.exec() == QDialog::Accepted) {
        SerialConfig newConfig = dialog.getConfig();
        newConfig.id = configId; // 保持ID不变

        // 更新数据库
        if (m_pSqliteManage->updateSerialConfig(newConfig)) {
            m_pLog->log(m_pSqliteManage,OPERATION_LOG,INFO,QString("修改设备串口配置"),m_pSqliteManage->getUserIdByName(username),config.device_id);
            // 重新加载配置
            loadSerialConfigs();

            // 更新已存在的监控点
            for (MonitorPointWidget *widget : m_monitorWidgets) {
                if (widget->config().id == configId) {
                    // 停止当前数据读取器
                    DataReader *oldReader = widget->config().id == configId ? widget->reader() : nullptr;
                    if (oldReader) {
                        oldReader->stopReading();
                        oldReader->deleteLater();
                    }

                    // 创建新的数据读取器
                    DataReader *newReader = new DataReader(newConfig, this);
                    widget->setDataReader(newReader);

                    // 更新标题
                    QLabel *titleLabel = widget->findChild<QLabel*>();
                    if (titleLabel) {
                        titleLabel->setText(newConfig.name + " (" + newConfig.portName + ")");
                    }

                }
            }
        } else {
            QMessageBox::critical(this, "错误", "无法更新串口配置");
        }
    }
}

void DataMonitor::deleteSerialConfig()
{
    // 获取选中的项
    QList<QTreeWidgetItem*> selectedItems = m_treeWidget->selectedItems();

    if (selectedItems.size() != 1)
        return;
    //qDebug()<<"size:"<<selectedItems.size();

    QTreeWidgetItem *item = selectedItems.first();
    int configId = item->data(0, Qt::UserRole).toInt();

    // 确认删除
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除", "确定要删除此串口配置吗？",
                                                                QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        // 检查是否有活动的监控点
        bool hasActiveMonitor = false;
        for (MonitorPointWidget *widget : m_monitorWidgets) {
            if (widget->config().id == configId) {
                hasActiveMonitor = true;
                break;
            }
        }

        if (hasActiveMonitor) {
            QMessageBox::warning(this, "警告", "此串口配置正在被使用，无法删除");
            return;
        }

        // 从数据库中删除
        if (m_pSqliteManage->deleteSerialConfig(configId)) {
            int device_id;
            m_pSqliteManage->getDeviceIdByName(item->text(0),device_id);///////////////////?
            m_pLog->log(m_pSqliteManage,OPERATION_LOG,WARNING,QString("删除设备串口配置"),
                        m_pSqliteManage->getUserIdByName(username));
            // 重新加载配置
            loadSerialConfigs();
        } else {
            QMessageBox::critical(this, "错误", "无法删除串口配置");
        }
    }
}



void DataMonitor::ensureWidgetVisible(QWidget *widget)
{
    // 滚动到指定的小部件
    m_scrollArea->ensureWidgetVisible(widget);

    // 高亮显示小部件（通过临时改变样式）
    QString originalStyle = widget->styleSheet();
    widget->setStyleSheet("background-color: #ffffcc; border: 2px solid #ffcc00; border-radius: 4px; margin: 5px;");

    // 1秒后恢复原始样式
    QTimer::singleShot(1000, [widget, originalStyle]() {
        widget->setStyleSheet(originalStyle);
    });
}

void DataMonitor::adjustScrollAreaSize()
{
    // 计算总高度（每个监控点高度 + 间距）
    int totalHeight = m_monitorWidgets.size() * (250 + m_chartLayout->spacing());
    m_chartContainer->setMinimumHeight(totalHeight);
    m_scrollArea->setMinimumHeight(qMin(totalHeight, 600));  // 限制最小高度
}

void DataMonitor::rearrangeGridLayout()
{
    // 重新排列为单列布局
    m_gridRow = 0;
    m_gridCol = 0;

    for (MonitorPointWidget *widget : m_monitorWidgets) {
        m_chartLayout->removeWidget(widget);
        m_chartLayout->addWidget(widget, m_gridRow, 0);  // 全部放在第0列
        m_gridRow++;  // 逐行排列
    }

    adjustScrollAreaSize();
}

void DataMonitor::loadSerialConfigs()
{
    // 清空树形控件
    m_treeWidget->clear();

    // 从数据库加载所有配置
    m_serialConfigs = m_pSqliteManage->getAllSerialConfigs();

    // 添加到树形控件
    for (const SerialConfig &config : m_serialConfigs) {
        QTreeWidgetItem *item = new QTreeWidgetItem(m_treeWidget);
        item->setText(0, config.name + " (" + config.portName + ")");
        item->setData(0, Qt::UserRole, config.id);
    }
}
